package org.irri.smta.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;

import org.irri.smta.config.IConfiguration;
import org.irri.smta.domain.Registry;
import org.irri.smta.repository.IRegistryRepository;
import org.irri.smta.service.IRegistryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

@Named("registryService")
@Transactional(readOnly = true)
public class RegistryService implements IRegistryService<Registry, Long> {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(RegistryService.class);

	@Inject
	@Named("registryRepository")
	private IRegistryRepository registryRepository;
	
	@Inject
	@Named("configuration")
	private IConfiguration configuration;

	@PostConstruct
	private void init() {
		if (configuration.isEmpty()) {
			configuration.load();
		}
	}

	public IConfiguration getConfiguration() {
		return configuration;
	}

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	@Override
	public Registry create(Registry registry) {
		LOGGER.debug("Registry create(Registry registry):" + registry);
		Date now = new Date();
		registry.setCreatedDate(now);
		registry.setUpdatedDate(now);
		LOGGER.debug("Creating a new application user with information: "
				+ registry);
		return registryRepository.save(registry);
	}

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	@Override
	public Registry update(Registry registry) throws Exception {
		LOGGER.debug("update(Registry registry): " + registry);
		registry.setUpdatedDate(new Date());
		LOGGER.debug("Updating user with information: " + registry);

		Registry registryDb = registryRepository.findOne(registry.getId());

		if (registryDb == null) {
			LOGGER.debug("No application user found with id: "
					+ registry.getId());
			throw new Exception();
		}

		registryRepository.save(registry);
		return registry;
	}

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	@Override
	public Registry delete(Long id) throws Exception {
		LOGGER.debug("Registry delete(Long id): " + id);

		Registry registry = registryRepository.findOne(id);

		if (registry == null) {
			LOGGER.debug("No user found with id: " + id);
			throw new Exception();
		}

		registryRepository.delete(registry);
		return registry;
	}

	@Transactional(readOnly = true)
	@Override
	public List<Registry> findAll() {
		LOGGER.debug("findAll() operation not supported!");
		return new ArrayList<Registry>();
	}

	@Transactional(readOnly = true)
	@Override
	public Registry findById(Long id) {
		LOGGER.debug("findById(Long id) operation not supported!");
		return null;
	}

}
